<?php

namespace api\user\controller;

use cmf\controller\RestBaseController;
use think\Validate;
use think\View;

class PublicController extends RestBaseController
{
    //系统初始化
    function init()
    {
        $this->success('success', [
            'customer_service_phone' => '4003898888'
        ]);
    }

    //登陆
    function login()
    {
        $validate = new Validate([
            'username' => 'require',
            'password' => 'require'
        ]);
        $validate->message([
            'username.require' => '请输入手机号!',
            'password.require' => '请输入您的密码!'
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error([
                'code' => 10001,
                'msg' => $validate->getError()
            ]);
        }

        $userQuery = db("user");
        if (Validate::is($data['username'], 'email')) {
            $userQuery = $userQuery->where('user_email', $data['username']);
        } else if (preg_match('/(^(13\d|15[^4\D]|17[013678]|18\d)\d{8})$/', $data['username'])) {
            $userQuery = $userQuery->where('mobile', $data['username']);
        } else {
            $userQuery = $userQuery->where('user_login', $data['username']);
        }

        $findUser = $userQuery->find();
        if (empty($findUser)) {
            $this->error([
                'code' => 10002,
                'msg' => "用户不存在!"
            ]);
        } else {
            switch ($findUser['user_status']) {
                case 0:
                    $this->error([
                        'code' => 10002,
                        'msg' => '该账号已停用，请联系客服!'
                    ]);
                case 2:
                    $this->error([
                        'code' => 10002,
                        'msg' => '账号尚未激活'
                    ]);
            }

            if (!cmf_compare_password($data['password'], $findUser['user_pass'])) {
                $this->error([
                    'code' => 10002,
                    'msg' => '密码不正确!'
                ]);
            }
        }

        $allowedDeviceTypes = ['mobile', 'android', 'iphone', 'ipad', 'web', 'pc', 'mac', 'ios'];

        if (empty($data['device_type']) || !in_array($data['device_type'], $allowedDeviceTypes)) {
            $this->error("请求错误,未知设备!");
        }

        $token = cmf_generate_user_token($findUser['id'], $data['device_type']);

        $data = [
            'user_nickname' => $findUser['user_nickname'],
            'mobile' => $findUser['mobile'],
            'user_email' => $findUser['user_email'],
            'sex' => $findUser['sex'],
            'birthday' => $findUser['birthday'] ? date('Y-m-d',$findUser['birthday']) : '未填写',
            'signature' => $findUser['signature'],
            'avatar' => cmf_get_image_url($findUser['avatar'] ?: '/static/images/headicon.png'),//$this->user['avatar'],
            'token' => $token
        ];
        $more = json_decode($findUser['more'], true);
        $data['wxcode'] = $more['wxcode'] ?? '';
        $data['address'] = $more['address'] ?? '';

        $this->success("登录成功!", $data);
    }

    /**
     * 验证码
     */
    function verification_code()
    {
        $validate = new Validate([
            'username' => 'require',
        ]);

        $validate->message([
            'username.require' => '请输入手机号!',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error([
                'code' => 10001,
                'msg' => $validate->getError()
            ]);
        }

        $accountType = '';

        if (Validate::is($data['username'], 'email')) {
            $accountType = 'email';
        } else if (preg_match('/(^(13\d|15[^4\D]|17[013678]|18\d)\d{8})$/', $data['username'])) {
            $accountType = 'mobile';
        } else {
            $this->error([
                'code' => 10001,
                'msg' => '请输入正确的手机号!'
            ]);
        }

        $code = cmf_get_verification_code($data['username']);
        if (empty($code)) {
            $this->error([
                'code' => 10001,
                'msg' => '验证码发送过多,请明天再试!'
            ]);
        }

        if ($accountType == 'email') {
            $emailTemplate = cmf_get_option('email_template_verification_code');

            $user = cmf_get_current_user();
            $username = empty($user['user_nickname']) ? $user['user_login'] : $user['user_nickname'];

            $message = htmlspecialchars_decode($emailTemplate['template']);
            $view = View::instance(config('template'), config('view_replace_str'));
            $message = $view->display($message, ['code' => $code, 'username' => $username]);
            $subject = empty($emailTemplate['subject']) ? 'ThinkCMF验证码' : $emailTemplate['subject'];
            $result = cmf_send_email($data['username'], $subject, $message);

            if (empty($result['error'])) {
                cmf_verification_code_log($data['username'], $code);
                $this->success("验证码已经发送成功!");
            } else {
                $this->error("邮箱验证码发送失败:" . $result['message']);
            }

        } else if ($accountType == 'mobile') {

            $param = ['mobile' => $data['username'], 'code' => $code];
            $result = hook_one("send_mobile_verification_code", $param);

            if ($result !== false && !empty($result['error'])) {
                $this->error($result['message']);
            }

            if ($result === false) {
                $this->error('验证码发送失败请联系客服!');
            }

            cmf_verification_code_log($data['username'], $code);

            if (!empty($result['message'])) {
                $this->success($result['message']);
            } else {
                $this->success('验证码已经发送成功!');
            }

        }
    }

    /**
     * 忘记密码
     */
    function password_reset()
    {
        $validate = new Validate([
            'username' => 'require',
            'password' => 'require|min:6|max:32',
            'verification_code' => 'require'
        ]);

        $validate->message([
            'username.require' => '请输入手机号!',
            'password.require' => '请输入您的密码!',
            'password.min' => '密码不能小于6个字符',
            'password.max' => '密码不能超过32个字符',
            'verification_code.require' => '请输入数字验证码!',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error([
                'code' => 10001,
                'msg' => $validate->getError()
            ]);
        }

        $userWhere = [];
        if (Validate::is($data['username'], 'email')) {
            $userWhere['user_email'] = $data['username'];
        } else if (preg_match('/(^(13\d|15[^4\D]|17[013678]|18\d)\d{8})$/', $data['username'])) {
            $userWhere['mobile'] = $data['username'];
        } else {
            $this->error([
                'code' => 10001,
                'msg' => '请输入正确的手机号!'
            ]);
        }

        $errMsg = cmf_check_verification_code($data['username'], $data['verification_code']);
        if (!empty($errMsg)) {
            $this->error([
                'code' => 10001,
                'msg' => $errMsg
            ]);
        }

        $user = db('user')->where($userWhere)->find();
        if (!$user) {
            $this->error([
                'code' => 10003,
                'msg' => '用户不存在'
            ]);
        }
        if ($user['user_status'] == 0) {
            $this->error([
                'code' => 10003,
                'msg' => '用户被禁用'
            ]);
        }
        $save = [
            'user_pass' => cmf_password($data['password'])
        ];
        if ($user['user_status'] == 4) {
            $save['user_status'] = 1;
        }
        db('user')->where($userWhere)->update($save);

        $this->success("密码重置成功,请使用新密码登录!");
    }
}